Gediz's exercise from Python 3.5 documentation - Tutorial

https://docs.python.org/3/tutorial/interpreter.html


In [12]:
#### Interpreter as a calculator
2+2


Out[12]:
4

In [13]:
# interpreter as a programming language  
width =10 
height = 45 
width*height


Out[13]:
450

In [89]:
#use answer as an argument (_)
_/45


Out[89]:
10.0

In [90]:
# strings, excape character \ and different quotes ' '' ''' " 
print('"doesn\'t it ?", he said.')


"doesn't it ?", he said.

In [91]:
# by adding (r) you can use raw strings. \n means new line 
print(r'C:\some\name','\n','C:\some\name')


C:\some\name 
 C:\some
ame

In [92]:
#span string litterals span multiple lines """...""" or '''...'''. 
#If you add \ at the end of a line it prevents new line.
print(""" 
What a wonderful world isn\'t it ? 
                Lol, it simply isn\'t!
""")


 
What a wonderful world isn't it ? 
                Lol, it simply isn't!


In [93]:
# it is possible to use some limited math while gluing strings
2*'a'+5*'i'+3*'!'


Out[93]:
'aaiiiii!!!'

In [94]:
'Py'+'thon'


Out[94]:
'Python'

In [95]:
#strings are immutable word[4]=r gives an error #strings are immutable
word='sunny'
word[1:3]
word[2:]


Out[95]:
'nny'

In [96]:
# by assignment lists are not copied only its pointer is assigned however a slice
# lets you copy the value of a list
squares = [1, 4, 9, 16, 25]
boxes=squares
quadras = squares[:]
squares[3]=0
boxes


Out[96]:
[1, 4, 9, 0, 25]

In [97]:
quadras


Out[97]:
[1, 4, 9, 16, 25]

In [98]:
#list itself is a class there are alot of methods for it 
quadras.append(202)
quadras.sort()
quadras


Out[98]:
[1, 4, 9, 16, 25, 202]

In [99]:
quadras.reverse()
quadras


Out[99]:
[202, 25, 16, 9, 4, 1]

In [100]:
# Here comes loops for fibonacci series 
a,b=1,10
while a<b :
    print (a)
    if a<b/2 :
        print('a is smaller than half of b')
    elif a==b/2:
        print ('a is equal to the half of b')
    else:
        print ('a is larger than half of b')
    a=a+1


1
a is smaller than half of b
2
a is smaller than half of b
3
a is smaller than half of b
4
a is smaller than half of b
5
a is equal to the half of b
6
a is larger than half of b
7
a is larger than half of b
8
a is larger than half of b
9
a is larger than half of b

In [101]:
# a for loop example 
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
    print(i, a[i])


0 Mary
1 had
2 a
3 little
4 lamb

In [102]:
# there are interesting break continue and pass statements in loops
# while break and continue are obvious pass is passed when an argument needed
# syntactically
class MyEmptyClass:
    pass #remember to impletement this
for num in range(2, 10):
    if num % 2 == 0:
        print("Found an even number", num)
        continue
    print("Found a number", num)


Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

In [103]:
# Defining funtions with a return value
def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=',')
        a, b = b, a+b
    print()
    return(b-a)

fib(5000)


0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,
Out[103]:
4181

In [104]:
#where is my function in memory 
func=fib
func


Out[104]:
<function __main__.fib>

In [105]:
# small anonymous functions can be created using lambda 
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs


Out[105]:
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

In [106]:
# Unpacking Arguments using * for list and ** for dictionaries
def concat(*args, sep="/"):
    return sep.join(args)
print(concat('a','b','c'))

def aFunc(what="I dont know",this=" this item"):
    print(what,this)

d={"what":"My parrot","this":"is a green bird "}
aFunc(**d)


a/b/c
My parrot is a green bird 

In [107]:
# there are default arguments values and keyword arguments 
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword
# these wouldn't work !
# parrot()                     # required argument missing
# parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
# parrot(110, voltage=220)     # duplicate value for the same argument
# parrot(actor='John Cleese')  # unknown keyword argument


-- This parrot wouldn't VOOOOOM if you put 1000000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !
-- This parrot wouldn't jump if you put a million volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's bereft of life !
-- This parrot wouldn't voom if you put a thousand volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's pushing up the daisies !

In [108]:
squares = list(map(lambda x: x**2, range(10)))
squares = [x**2 for x in range(10)]
squares


Out[108]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [109]:
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]


Out[109]:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

In [110]:
[x**3 for x in range(5,20,3)]


Out[110]:
[125, 512, 1331, 2744, 4913]

In [111]:
t = range(1,5),'xero',231/2 # a tuple is immutable
print(t)


(range(1, 5), 'xero', 115.5)

In [112]:
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} # is a set
print(basket)


{'banana', 'apple', 'pear', 'orange'}

In [113]:
a=set('gediz gürsu') # a set reduces to unique letters ...
b=set('giresun')
print(a,a|b,a^b,a-b)


{'i', 'r', 'u', ' ', 'z', 'ü', 'd', 'g', 's', 'e'} {'n', 'i', 'r', 'u', ' ', 'z', 'ü', 'd', 'g', 's', 'e'} {'z', 'd', 'n', ' ', 'ü'} {' ', 'z', 'ü', 'd'}

In [178]:
mydict=dict(sape=4139, guido=4127, jack=4098) # dictionary is a basic data type
{x: x**2 for x in (2, 4, 6)}


Out[178]:
{2: 4, 4: 16, 6: 36}

In [115]:
# lists can be used as different data types such as stacks queues 
from collections import deque #faster operations ...
queue = deque(["Eric", "John", "Michael"])
queue.popleft() 
queue


Out[115]:
deque(['John', 'Michael'])

In [155]:
# matrix transposition
matrix = [
     [1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12],]


[[row[i] for row in matrix] for i in range(4)]


Out[155]:
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

In [156]:
list(zip(*matrix)) #


Out[156]:
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

In [162]:
%%HTML
<h1 style="color:blue;font-family:verdana;font-size:16px">This is my Design</h1>


This is my Design


In [157]:
del matrix[0]
matrix


Out[157]:
[[5, 6, 7, 8], [9, 10, 11, 12]]

In [158]:
t = 12345, 54321, 'hello!',matrix  #tuples are useful I guess ...
t


Out[158]:
(12345, 54321, 'hello!', [[5, 6, 7, 8], [9, 10, 11, 12]])

In [183]:
for i in enumerate(reversed(t)):
    print(i)
print ('\n')
for i,j in mydict.items():
    print(i,j)


(0, [[5, 6, 7, 8], [9, 10, 11, 12]])
(1, 'hello!')
(2, 54321)
(3, 12345)


sape 4139
guido 4127
jack 4098

In [190]:
#modules fibo.py  __name__ as global variable 
if __name__ == "__main__":
    import sys

# fib(int(sys.argv[1])) #to use fibo.sys as script do the following
# >>> python fibo.py 50 #to use it from command prompt

# When a module is  it first looks for the standard modules then for .py
sys.path.append("""C:/Users/gediz/Documents""")
sys.path


Out[190]:
['',
 'C:\\Program Files\\Blender Foundation\\Blender\\2.76\\scripts\\modules',
 'C:\\Users\\gediz\\Anaconda3\\python35.zip',
 'C:\\Users\\gediz\\Anaconda3\\DLLs',
 'C:\\Users\\gediz\\Anaconda3\\lib',
 'C:\\Users\\gediz\\Anaconda3',
 'c:\\users\\gediz\\anaconda3\\lib\\site-packages\\setuptools-19.2-py3.5.egg',
 'C:\\Users\\gediz\\Anaconda3\\lib\\site-packages',
 'C:\\Users\\gediz\\Anaconda3\\lib\\site-packages\\Sphinx-1.3.1-py3.5.egg',
 'C:\\Users\\gediz\\Anaconda3\\lib\\site-packages\\cryptography-1.0.2-py3.5-win-amd64.egg',
 'C:\\Users\\gediz\\Anaconda3\\lib\\site-packages\\win32',
 'C:\\Users\\gediz\\Anaconda3\\lib\\site-packages\\win32\\lib',
 'C:\\Users\\gediz\\Anaconda3\\lib\\site-packages\\Pythonwin',
 'C:\\Users\\gediz\\Anaconda3\\lib\\site-packages\\IPython\\extensions',
 'C:\\Users\\gediz\\.ipython',
 'C:/Users/gediz/Documents',
 'C:/Users/gediz/Documents']

In [193]:
import builtins
dir(builtins)


Out[193]:
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BlockingIOError',
 'BrokenPipeError',
 'BufferError',
 'BytesWarning',
 'ChildProcessError',
 'ConnectionAbortedError',
 'ConnectionError',
 'ConnectionRefusedError',
 'ConnectionResetError',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FileExistsError',
 'FileNotFoundError',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'ImportError',
 'ImportWarning',
 'IndentationError',
 'IndexError',
 'InterruptedError',
 'IsADirectoryError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'NameError',
 'None',
 'NotADirectoryError',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'PermissionError',
 'ProcessLookupError',
 'RecursionError',
 'ReferenceError',
 'ResourceWarning',
 'RuntimeError',
 'RuntimeWarning',
 'StopAsyncIteration',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'TimeoutError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'WindowsError',
 'ZeroDivisionError',
 '__IPYTHON__',
 '__IPYTHON__active',
 '__build_class__',
 '__debug__',
 '__doc__',
 '__import__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'abs',
 'all',
 'any',
 'ascii',
 'bin',
 'bool',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'divmod',
 'dreload',
 'enumerate',
 'eval',
 'exec',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'vars',
 'zip']

In [196]:
# import sound.effects.echo
# from sound.effects import echo
# from sound.effects.echo import echofilter
# from sound.effects import *
# if package has __all__  as __all__ = ["echo", "surround", "reverse"] 
# then * imports these submodules

In [198]:
print('{0} and {1}'.format('spam', 'eggs'))
print('We are the {} who say "{}!"'.format('knights', 'Ni'))

for x in range(1, 11):
    print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))


spam and eggs
We are the knights who say "Ni!"
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

In [1]:
f = open('workfile', 'r+') # w r r+ a b-> binary other than text files
f.write('This is a test\n')
f.readline()


Out[1]:
'This is a test\n'

In [11]:
f.seek(5) # go to the 5th byte or binary ...
f.read(9)


Out[11]:
'is a test'

In [205]:
f.tell() # current position in file


Out[205]:
8

In [217]:
f.close()
f.closed


Out[217]:
True

In [228]:
import json
json.dumps([1,2,3])
f = open('workfile', 'r+')
json.dumps([1,2,3],f)


Out[228]:
'[1, 2, 3]'

In [224]:
f.closed


Out[224]:
False

In [229]:
raise NameError('HiThere')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-229-93385ba972b1> in <module>()
----> 1 raise NameError('HiThere')

NameError: HiThere

In [236]:
def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else:
        print("result is", result)
    finally:
        print("executing finally clause")

divide (5,0)


division by zero!
executing finally clause

In [237]:
class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'
x = MyClass()

In [245]:
x.f()


Out[245]:
'hello world'

In [246]:
x.counter=100
x.counter


Out[246]:
100

In [248]:
# instance variables in class default namespace is shared by instances (strangely)
# therefore each variable regarding to this instance should be located under _init_

class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)
    
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
e.tricks


Out[248]:
['play dead']

In [257]:
class mytestclass:
    
    def __init__(self,name):
        self.name=name
        self.tests=[]
        
    def add_test(self,test):
        self.tests.append(test)
        
myclass = mytestclass('first test')    
myclass.add_test('testere')
myclass.tests


Out[257]:
['testere']

In [263]:
class myoverrideclass(mytestclass):  #overriding overloading functions ...
    def add_test(self,test): #overriding works
        print('this is an overriden class')

    #  def add_test(self,test1,test2): #  overloading does not work 
    #    self.tests.append(test1)
    #    self.tests.append(test2)
        
myclass = myoverrideclass('test2')
myclass.add_test('testere')
myclass.tests


this is an overriden class
Out[263]:
[]

In [267]:
%%HTML 
<h1 style="color:red;font-family:verdana;font-size:16px">
Overloading is not required since we able to omit arguments  </h1>
<a href="http://stackoverflow.com/questions/10202938/how-do-i-use-method-overloading-in-python">
Visit Stackoverflow subject </a>


Overloading is not required since we able to omit arguments

Visit Stackoverflow subject

Here comes Standard Library Modules ...


In [ ]:
# Help and lookup functions and system functions...
# import os
# print(dir(sys))
# help(os)
# import pip
# help(pip)

In [26]:
%lsmagic


Out[26]:
Available line magics:
%alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %install_default_config  %install_ext  %install_profiles  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.

In [12]:
%cls?

In [28]:
from IPython.display import HTML, SVG, YouTubeVideo
YouTubeVideo('j9YpkSX7NNM')


Out[28]:

In [36]:


In [ ]: